package com.example.netty;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class ControlActivity extends AppCompatActivity {

    private static final String SERVER_IP = "192.168.3.39";
    private static final int SERVER_PORT = 9999;

    //实现跳转
    private Button cBtFan;
    private Button cBtBeep;
    private Button cBtLed;

    private Socket socket;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_control);

        cBtFan = findViewById(R.id.cfan);
        cBtBeep = findViewById(R.id.beep);
        cBtLed = findViewById(R.id.cled);

        cBtFan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendStringToServer("front-end:String=fan");
            }
        });

        cBtBeep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendStringToServer("front-end:String=beep");
            }
        });

        cBtLed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendStringToServer("front-end:String=led");
            }
        });
    }

    private void sendStringToServer(String message) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 创建Socket对象，连接服务器
                    socket = new Socket(SERVER_IP, SERVER_PORT);

                    OutputStream outputStream = socket.getOutputStream();
                    outputStream.write(message.getBytes());

                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

